package com.huilian.iotbox.admin.wap.service.impl;

import com.huilian.iotbox.admin.wap.dao.PushConfigDao;
import com.huilian.iotbox.admin.wap.dao.PushConfigItemDao;
import com.huilian.iotbox.admin.wap.service.PushConfigService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.PushConfigDto;
import com.huilian.iotbox.data.enums.PushConfigLevelEnum;
import com.huilian.iotbox.data.enums.PushConfigStatusEnum;
import com.huilian.iotbox.data.vo.PushConfigItemVo;
import com.huilian.iotbox.data.vo.PushConfigVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author LinYinDong
 * @date 2024/1/9 10:58
 */
@Service
public class PushConfigServiceImpl implements PushConfigService {
    @Resource
    private PushConfigDao pushConfigDao;
    @Resource
    private PushConfigItemDao pushConfigItemDao;

    @Override
    public ServerResponse findPushConfigList(PushConfigDto pushConfigDto) {
        pushConfigDto.setStatus(PushConfigStatusEnum.GROUNDING.getCode());
        pushConfigDto.setLevel(PushConfigLevelEnum.ONE_LEVE.getCode());

        //查询所有的消息通知项
        List<PushConfigVo> pushConfigList = pushConfigDao.findPushConfigList(pushConfigDto);

        //根据userId查询开启的消息通知项
        List<PushConfigItemVo> pushConfigItemVoList = pushConfigItemDao.getPushConfigByUserIdList(pushConfigDto);
        if (StringUtils.isEmpty(pushConfigItemVoList) || pushConfigItemVoList.size() == 0) {
            //初始化 开关值为true
            pushConfigList.forEach(item -> {
                item.getChildList().forEach(data -> {
                    data.setIsOpen(false);
                });
            });
            return ServerResponse.createBySuccess(pushConfigList);
        }

        //根据userId设置 开启了为true否则为false
        pushConfigList.forEach(item -> {
            item.getChildList().forEach(data -> {
                Boolean aBoolean = this.checkIsOpen(data, pushConfigItemVoList);
                data.setIsOpen(aBoolean);
            });
        });
        return ServerResponse.createBySuccess(pushConfigList);
    }

    private Boolean checkIsOpen(PushConfigVo data, List<PushConfigItemVo> pushConfigItemVoList) {
        Boolean flog = false;
        for (PushConfigItemVo pushConfigItemVo : pushConfigItemVoList) {
            if (data.getId().equals(pushConfigItemVo.getPushConfigId())) {
                flog = pushConfigItemVo.getIsOpen();
            }
        }
        return flog;
    }

}
